#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

class Solution{
    public:
    vector<int> ans1(vector<vector<int>>& matrix){
        int rows = matrix.size();
        int cols = matrix[0].size();
        int len = rows * cols;
        vector<int> ret;

        int i = 0, j = 0;
        int r = cols, b = rows, l = 0, t = 0;
        while(true){
            for(j = l; j != r; j++){
                ret.push_back(matrix[i][j]);
            }
            j--;
            t++;
            if(t >= b){
                break;
            }
            for(i = t; i != b; i++){
                ret.push_back(matrix[i][j]);
            }
            i--;
            r--;
            if(r <= l){
                break;
            }
            for(j = r-1; j >= l; j--){
                ret.push_back(matrix[i][j]);
            }
            j++;
            b--;
            if(b <= t){
                break;
            }
            for(i = b-1; i >= t; i--){
                ret.push_back(matrix[i][j]);
            }
            i++;
            l++;
            if(l >= r){
                break;
            }
            
        }
        return ret;
        
    }

    void show(vector<int>& num){
        int len = num.size();
        for(int i = 0; i != len-1; i++){
            cout << num[i] << " " << ends;
        }
        cout << num[len-1] << endl;
    }
};

void test1(){
    Solution s;
    vector<vector<int>> val = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    vector<int> ret = s.ans1(val);
    s.show(ret);

}

void test2(){
    Solution s;
    vector<vector<int>> val = {
        {1,2,3,4},
        {5,6,7,8},
        {9,10,11,12}
    };
    vector<int> ret = s.ans1(val);
    s.show(ret);

}

int main(void){
    test1();
    test2();

    return 0;
}